package org.stvd.common.security.support;

import java.security.KeyFactory;
import java.security.PublicKey;
import java.security.Signature;
import java.security.spec.X509EncodedKeySpec;
import java.text.ParseException;

import org.springframework.security.crypto.codec.Base64;
import org.stvd.core.util.DateUtil;
 
 
public class SysAuthentication {
 
    //licenseText
    private String code = "MjAxNjEyMjB7RTk3MzAyQTUtMDIwMy0xQkFFLTBBNTItMkM4MUFBRjYxNUE4fXN0dmQyMDE2MTIyMDIwMTgwMzMw" ;
    //signdText
    private String value = "vtYpxmrw0bK0GRyUbyLfxRkjgBVsEUSZl3CMYVt52EkQ0ryfbjD5PtZk6CPJSMTFWykPMczPjqSLoXT74mt5Iya1YJWiLUQVBvaVOFFkJHtXTwy46iAPyNomxtmnZo+FkJ2AU/Ye+B6o85gfSn2ekGZpJckj7ntRZ2T5EK0Si1s=" ;
    //pubKey
    private String pub = "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQD0Fnr1rEwp0El3TbtyLWA4mPGG1FQsAI4t/ku9EiTxEFUH1DmJBtkj2He4g3O0KQTqOXbvBV8uETKIMeZAnQ1u2M4SYZZ2AmLl/GYPTd1j6+c1SGPc0Pffmcc6lrjxhFx5rYilgQ3cBgmjIpfrKsapmnUjk5TE+J28KjHdiMiweQIDAQAB";
    private boolean verify(byte[] pubKeyText, String plainText, byte[] signText) { 
        try { 
            // 解密由base64编码的公钥,并构造X509EncodedKeySpec对象 
            X509EncodedKeySpec bobPubKeySpec = new X509EncodedKeySpec(Base64.decode(pubKeyText)); 
            // RSA对称加密算法 
            KeyFactory keyFactory = KeyFactory.getInstance("RSA"); 
            // 取公钥匙对象 
            PublicKey pubKey = keyFactory.generatePublic(bobPubKeySpec); 
            // 解密由base64编码的数字签名 
            byte[] signed = Base64.decode(signText); 
            Signature signatureChecker = Signature.getInstance("MD5withRSA"); 
            signatureChecker.initVerify(pubKey); 
            signatureChecker.update(plainText.getBytes()); 
            // 验证签名是否正常 
            if (signatureChecker.verify(signed)) 
                return true; 
            else 
                return false; 
        } catch (Throwable e) { 
//            System.out.println("校验签名失败"); 
//            e.printStackTrace(); 
            return false;
        } 
    }

    public boolean verify(){
        String version = new String(Base64.decode(code.getBytes()));
        
        try {
            if(!DateUtil.beforDate2(DateUtil.getSystemDateOfY2D(),
                    version.substring(version.length() - 8))){
                return false ;
            } else {
                return verify(pub.getBytes(), code, value.getBytes());
            }
        } catch (ParseException e) {
            return false ;
        }
    }
    
    public static void main(String[] args) {
        SysAuthentication sysAuthentication = new SysAuthentication();
        System.out.println(sysAuthentication.verify());
    }
}